/*
 ************************************************************************************
 * Copyright (C) 2009-2010 Openbravo S.L.U.
 * Licensed under the Openbravo Commercial License version 1.0
 * You may obtain a copy of the License at http://www.openbravo.com/legal/obcl.html
 * or in the legal folder of this module distribution.
 ************************************************************************************
 */

package org.openbravo.furniture.form;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.io.File;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.openbravo.base.secureApp.HttpSecureAppServlet;
import org.openbravo.base.secureApp.VariablesSecureApp;
import org.openbravo.erpCommon.businessUtility.WindowTabs;
import org.openbravo.erpCommon.reference.ActionButtonData;
import org.openbravo.erpCommon.reference.PInstanceProcessData;
import org.openbravo.erpCommon.utility.ComboTableData;
import org.openbravo.erpCommon.utility.LeftTabsBar;
import org.openbravo.erpCommon.utility.NavigationBar;
import org.openbravo.erpCommon.utility.OBError;
import org.openbravo.erpCommon.utility.SequenceIdData;
import org.openbravo.erpCommon.utility.ToolBar;
import org.openbravo.erpCommon.utility.Utility;
import org.openbravo.exception.NoConnectionAvailableException;
import org.openbravo.xmlEngine.XmlDocument;

public class Prod_import extends HttpSecureAppServlet {
  private static final long serialVersionUID = 1L;

  static final int THRESHOLD = 1000;

  public void init(ServletConfig config) {
    super.init(config);
    boolHist = false;
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    VariablesSecureApp vars = new VariablesSecureApp(request);

    if (vars.commandIn("DEFAULT")) {
      printPage(response, vars);

    } else if (vars.commandIn("SAVE")) {

      OBError myMessage = new OBError();
      myMessage.setTitle("");

      String loggingText;
      String errText;

      String catalogo = vars.getStringParameter("inpCatalogo");
      String coCo = vars.getStringParameter("inpCoefCompra");
      String coVe = vars.getStringParameter("inpCoefVenta");
      String partnerId = vars.getStringParameter("inpcBpartnerId");
      // String file = vars.getStringParameter("inpFile");
      FileItem fi = vars.getMultiFile("inpFile");
      String file = fi.getName();

      try {
        final File uploadedDir = new File(globalParameters.strFTPDirectory + "/cargaproductos");
	//final File uploadedDir = new File("/tmp/cargaproductos");
        if (!uploadedDir.exists()) uploadedDir.mkdirs();
        final File uploadedFile = new File(uploadedDir, file);
        fi.write(uploadedFile);
      } catch (final Exception ex) {
        throw new ServletException(ex);
      }
                                                                                 

      /* Cargo fichero en tabla temporal */

      try {
        //myMessage = processImport(globalParameters.strFTPDirectory + "/cargaproductos/" + file, vars);
        myMessage = processImport(file, vars, partnerId);
      } catch (ServletException ex) {
        myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
        myMessage.setMessage(Utility.messageBD(this, "Created", vars.getLanguage()));
      } catch (NoConnectionAvailableException ex2) {
        myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex2.getMessage());
        myMessage.setMessage(Utility.messageBD(this, "Created", vars.getLanguage()));
      } catch (SQLException ex3) {
        myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex3.getMessage());
        myMessage.setMessage(Utility.messageBD(this, "Created", vars.getLanguage()));
      }

      /* Si la carga va OK, ejecutamos proceso de carga */

      try {
              if (myMessage.getType().equals("Success"))  {
        myMessage = processCarga(file, catalogo, coCo, coVe, partnerId, vars);
	          }
      } catch (ServletException ex) {
        myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
        myMessage.setMessage(Utility.messageBD(this, "Created", vars.getLanguage()));
      } catch (NoConnectionAvailableException ex2) {
        myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex2.getMessage());
        myMessage.setMessage(Utility.messageBD(this, "Created", vars.getLanguage()));
      } catch (SQLException ex3) {
        myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex3.getMessage());
        myMessage.setMessage(Utility.messageBD(this, "Created", vars.getLanguage()));
      }

/*      myMessage.setType("Success");
      myMessage.setTitle(Utility.messageBD(this, "PRODIMPORT_SUCCESS", vars.getLanguage()));
      myMessage.setMessage("");*/
      vars.setMessage("Prod_import", myMessage);
      printPage(response, vars);

    } else {
      pageError(response);
    }
  }

  void printPage(HttpServletResponse response, VariablesSecureApp vars) throws IOException,
      ServletException {

    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/furniture/form/Prod_import")
        .createXmlDocument();

    ToolBar toolbar = new ToolBar(this, vars.getLanguage(), "Prod_import", false, "", "", "",
        false, "ad_forms", strReplaceWith, false, true);
    toolbar.prepareSimpleToolBarTemplate();
    xmlDocument.setParameter("toolbar", toolbar.toString());

    try {
      WindowTabs tabs = new WindowTabs(this, vars, "org.openbravo.furniture.form.Prod_import");
      xmlDocument.setParameter("parentTabContainer", tabs.parentTabs());
      xmlDocument.setParameter("mainTabContainer", tabs.mainTabs());
      xmlDocument.setParameter("childTabContainer", tabs.childTabs());
      xmlDocument.setParameter("theme", vars.getTheme());

      ComboTableData comboTableData = new ComboTableData(vars, this, "TABLE", "C_BPartner_ID",
          "C_BPartner Vendors", "", Utility.getContext(this, vars, "#AccessibleOrgTree", "Prod_import"),
          Utility.getContext(this, vars, "#User_Client", "Prod_import"), 0);
      Utility.fillSQLParameters(this, vars, null, comboTableData, "Prod_import", "");
      xmlDocument.setData("reportC_BPARTNERID", "liststructure", comboTableData.select(false));
      comboTableData = null;

      NavigationBar nav = new NavigationBar(this, vars.getLanguage(), "Prod_import.html",
          classInfo.id, classInfo.type, strReplaceWith, tabs.breadcrumb());
      xmlDocument.setParameter("navigationBar", nav.toString());
      LeftTabsBar lBar = new LeftTabsBar(this, vars.getLanguage(), "Prod_import.html",
          strReplaceWith);
      xmlDocument.setParameter("leftTabs", lBar.manualTemplate());
    } catch (Exception ex) {
      throw new ServletException(ex);
    }
    OBError myMessage = null;
    {
      /*OBError myMessage = vars.getMessage("Prod_import");
      vars.removeMessage("Prod_import");
      if (myMessage != null) {
        xmlDocument.setParameter("messageType", myMessage.getType());
        xmlDocument.setParameter("messageTitle", myMessage.getTitle());
        xmlDocument.setParameter("messageMessage", myMessage.getMessage());
      }*/
     {
        myMessage = vars.getMessage("Prod_import");
        vars.removeMessage("Prod_import");
         if (myMessage != null) {
          xmlDocument.setParameter("messageType", myMessage.getType());
          xmlDocument.setParameter("messageTitle", myMessage.getTitle());
          xmlDocument.setParameter("messageMessage", myMessage.getMessage());
	  log4j.error("Import product - type: "+myMessage.getType());
	  log4j.error("Import product - type: "+myMessage.getTitle());
	  log4j.error("Import product - type: "+myMessage.getMessage());
        }
      }


      String log = "";
      vars.removeSessionValue("logMessage");
      xmlDocument.setParameter("inplog", log);

      String err = vars.getSessionValue("errMessage");
      vars.removeSessionValue("errMessage");
      xmlDocument.setParameter("inperr", err);

      xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n");
      xmlDocument.setParameter("paramLanguage", "defaultLang=\"" + vars.getLanguage() + "\";");

      response.setContentType("text/html; charset=UTF-8");
      PrintWriter out = response.getWriter();
      out.println(xmlDocument.print());
      out.close();
    }

  }

  private OBError processImport(String file, VariablesSecureApp vars, String partnerId) throws ServletException,
      NoConnectionAvailableException, SQLException {
    Connection conn = null;
    conn = getTransactionConnection();

    OBError myMessage = null;
    myMessage = new OBError();
    myMessage.setTitle("");

    String pinstance = SequenceIdData.getUUID();
    try {
      PInstanceProcessData.insertPInstance(this, pinstance, "34BE021A9CEC4847BB405BBE186EC859",
          "0", "N", vars.getUser(), vars.getClient(), "0");
      PInstanceProcessData.insertPInstanceParam(this, pinstance, "10", "File", file,
          vars.getClient(), vars.getOrg(), vars.getUser());
    } catch (ServletException ex) {
      myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
      releaseRollbackConnection(conn);
      return myMessage;
    }

    ActionButtonData.process34BE021A9CEC4847BB405BBE186EC859(this, pinstance);
    PInstanceProcessData[] pinstanceData = PInstanceProcessData.select(this, pinstance);
    myMessage = Utility.getProcessInstanceMessage(this, vars, pinstanceData);

    releaseCommitConnection(conn);

    return myMessage;
  }

  private OBError processCarga(String file, String catalogo, String coCo, String coVe,
      String partnerId, VariablesSecureApp vars) throws ServletException,
      NoConnectionAvailableException, SQLException {
    Connection conn = null;
    conn = getTransactionConnection();

    OBError myMessage = null;
    myMessage = new OBError();
    myMessage.setTitle("");
    String pinstance = SequenceIdData.getUUID();

    try {
      PInstanceProcessData.insertPInstance(this, pinstance, "A9BED7050B5A451B906A27714F332C0D",
          "0", "N", vars.getUser(), vars.getClient(), "0");
      PInstanceProcessData.insertPInstanceParam(this, pinstance, "5", "File", file,
          vars.getClient(), vars.getOrg(), vars.getUser());
      PInstanceProcessData.insertPInstanceParam(this, pinstance, "10", "Catalogo", catalogo,
          vars.getClient(), vars.getOrg(), vars.getUser());
      PInstanceProcessData.insertPInstanceParam(this, pinstance, "20", "coCo", coCo,
          vars.getClient(), vars.getOrg(), vars.getUser());
      PInstanceProcessData.insertPInstanceParam(this, pinstance, "30", "coVe", coVe,
          vars.getClient(), vars.getOrg(), vars.getUser());
      PInstanceProcessData.insertPInstanceParam(this, pinstance, "40", "C_BPartner_Id", partnerId,
          vars.getClient(), vars.getOrg(), vars.getUser());
    } catch (ServletException ex) {
      myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
      releaseRollbackConnection(conn);
      return myMessage;
    }

    ActionButtonData.processA9BED7050B5A451B906A27714F332C0D(this, pinstance);
    PInstanceProcessData[] pinstanceData = PInstanceProcessData.select(this, pinstance);
    myMessage = Utility.getProcessInstanceMessage(this, vars, pinstanceData);

    releaseCommitConnection(conn);

    return myMessage;
  }

  public String getServletInfo() {
    return "Servlet that presents the files-importing process";
    // end of getServletInfo() method
  }

}
